<template>
  <div class="users-container">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总用户数</span>
            </div>
          </template>
          <div class="card-content" v-loading="loading">
            <h2>{{ userAnalysisData.totalUserCount.toLocaleString() }}</h2>
            <p>较上月 <span :class="getGrowthClass(userAnalysisData.totalUserGrowth)">
              {{ getGrowthText(userAnalysisData.totalUserGrowth) }}
            </span></p>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>新增用户</span>
            </div>
          </template>
          <div class="card-content" v-loading="loading">
            <h2>{{ userAnalysisData.newUserCount.toLocaleString() }}</h2>
            <p>较上月 <span :class="getGrowthClass(userAnalysisData.newUserGrowth)">
              {{ getGrowthText(userAnalysisData.newUserGrowth) }}
            </span></p>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>活跃用户</span>
            </div>
          </template>
          <div class="card-content" v-loading="loading">
            <h2>{{ userAnalysisData.activeUserCount.toLocaleString() }}</h2>
            <p>较上月 <span :class="getGrowthClass(userAnalysisData.activeUserGrowth)">
              {{ getGrowthText(userAnalysisData.activeUserGrowth) }}
            </span></p>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>客单价</span>
            </div>
          </template>
          <div class="card-content" v-loading="loading">
            <h2>¥{{ userAnalysisData.averageOrderAmount.toFixed(2) }}</h2>
            <p>较上月 <span :class="getGrowthClass(userAnalysisData.averageOrderGrowth)">
              {{ getGrowthText(userAnalysisData.averageOrderGrowth) }}
            </span></p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>用户增长趋势</span>
            </div>
          </template>
          <div class="chart-container" v-loading="loading">
            <div ref="userGrowthChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>用户地域分布</span>
            </div>
          </template>
          <div class="chart-container" v-loading="loading">
            <div ref="userRegionChartRef" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户列表 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>用户列表</span>
              <div class="search-box">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索用户"
                  style="width: 200px;"
                  clearable
                  @keyup.enter="handleSearch"
                  @clear="handleSearch"
                />
                <el-button type="primary" @click="handleSearch" style="margin-left: 10px;">搜索</el-button>
              </div>
            </div>
          </template>
          <el-table :data="userAnalysisData.userList" style="width: 100%" border v-loading="loading">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="registerTime" label="注册时间" width="180" />
            <el-table-column prop="lastLoginTime" label="最后登录" width="180" />
            <el-table-column prop="orderCount" label="订单数" width="100" />
            <el-table-column prop="totalSpent" label="消费总额" width="150">
              <template #default="scope">
                ¥{{ scope.row.totalSpent.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" @click="viewUserDetail(scope.row)">查看详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="(size: number) => { pageSize = size; fetchUserAnalysisData(); }"
              @current-change="handlePageChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 用户详情对话框 -->
    <el-dialog
      title="用户详情"
      v-model="userDetailVisible"
      width="60%"
    >
      <div v-if="currentUser">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">{{ currentUser.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ currentUser.username }}</el-descriptions-item>
          <el-descriptions-item label="注册时间">{{ currentUser.registerTime }}</el-descriptions-item>
          <el-descriptions-item label="最后登录">{{ currentUser.lastLoginTime }}</el-descriptions-item>
          <el-descriptions-item label="订单数">{{ currentUser.orderCount }}</el-descriptions-item>
          <el-descriptions-item label="消费总额">¥{{ currentUser.totalSpent.toFixed(2) }}</el-descriptions-item>
        </el-descriptions>

        <h3 style="margin-top: 20px;">消费记录</h3>
        <el-table :data="userOrders" style="width: 100%" border>
          <el-table-column prop="id" label="订单ID" width="100" />
          <el-table-column prop="date" label="下单时间" width="180" />
          <el-table-column prop="amount" label="订单金额" width="150">
            <template #default="scope">
              ¥{{ scope.row.amount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="订单状态" width="120">
            <template #default="scope">
              <el-tag :type="getOrderStatusType(scope.row.status)">
                {{ getOrderStatusName(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { getUserAnalysis } from '@/api/merchant'
import * as echarts from 'echarts'

// 加载状态
const loading = ref(false)

// 搜索关键词
const searchKeyword = ref('')

// 图表引用
const userGrowthChartRef = ref<HTMLElement | null>(null)
const userRegionChartRef = ref<HTMLElement | null>(null)
let userGrowthChart: echarts.ECharts | null = null
let userRegionChart: echarts.ECharts | null = null

// 用户分析数据
const userAnalysisData = reactive({
  totalUserCount: 0,
  newUserCount: 0,
  activeUserCount: 0,
  averageOrderAmount: 0,
  totalUserGrowth: 0,
  newUserGrowth: 0,
  activeUserGrowth: 0,
  averageOrderGrowth: 0,
  userGrowthTrend: [] as any[],
  userRegionDistribution: [] as any[],
  userList: [] as any[]
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 用户详情相关
const userDetailVisible = ref(false)
const currentUser = ref<any>(null)
const userOrders = ref<Order[]>([])

interface Order {
  id: number;
  date: string;
  amount: number;
  status: string;
}

// 获取用户分析数据
const fetchUserAnalysisData = async () => {
  loading.value = true
  try {
    const response = await getUserAnalysis({
      keyword: searchKeyword.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })

    if (response.data.code === 200) {
      // 更新用户分析数据
      Object.assign(userAnalysisData, response.data.data)

      // 更新分页数据
      if (response.data.data.userList) {
        total.value = response.data.data.total || 0
      }

      // 渲染图表
      renderCharts()
    }
  } catch (error) {
    console.error('获取用户分析数据失败:', error)
    ElMessage.error('获取用户分析数据失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchUserAnalysisData()
}

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchUserAnalysisData()
}

// 查看用户详情
const viewUserDetail = async (user: any) => {
  currentUser.value = user
  userDetailVisible.value = true

  try {
    const loadingInstance = ElLoading.service({ fullscreen: true, text: '加载中...' })

    // 获取用户订单数据
    const response = await getUserAnalysis({ userId: user.id })
    if (response.data.code === 200 && response.data.data.userOrders) {
      userOrders.value = response.data.data.userOrders
    } else {
      // 模拟数据
      userOrders.value = [
        {
          id: 10001,
          date: '2023-05-15 14:25:36',
          amount: 128.50,
          status: 'completed'
        },
        {
          id: 10002,
          date: '2023-05-10 09:15:22',
          amount: 256.80,
          status: 'completed'
        },
        {
          id: 10003,
          date: '2023-05-05 16:40:18',
          amount: 95.20,
          status: 'completed'
        }
      ]
    }

    loadingInstance.close()
  } catch (error) {
    console.error('获取用户订单数据失败:', error)
    ElMessage.error('获取用户订单数据失败')
  }
}

// 获取订单状态名称
const getOrderStatusName = (status: string) => {
  const statusMap: Record<string, string> = {
    'pending': '待付款',
    'processing': '处理中',
    'shipping': '配送中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

// 获取订单状态标签类型
const getOrderStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    'pending': 'warning',
    'processing': 'info',
    'shipping': 'primary',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return typeMap[status] || ''
}

// 获取增长率显示样式
const getGrowthClass = (growth: number) => {
  return growth >= 0 ? 'up' : 'down'
}

// 获取增长率显示文本
const getGrowthText = (growth: number) => {
  const prefix = growth >= 0 ? '+' : ''
  return `${prefix}${growth.toFixed(1)}%`
}

// 渲染图表
const renderCharts = () => {
  nextTick(() => {
    // 用户增长趋势图表
    if (userGrowthChartRef.value) {
      if (!userGrowthChart) {
        userGrowthChart = echarts.init(userGrowthChartRef.value)
      }

      const userGrowthOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['总用户数', '新增用户', '活跃用户']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: userAnalysisData.userGrowthTrend.map(item => item.date)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '总用户数',
            type: 'line',
            data: userAnalysisData.userGrowthTrend.map(item => item.totalUserCount)
          },
          {
            name: '新增用户',
            type: 'bar',
            data: userAnalysisData.userGrowthTrend.map(item => item.newUserCount)
          },
          {
            name: '活跃用户',
            type: 'line',
            data: userAnalysisData.userGrowthTrend.map(item => item.activeUserCount)
          }
        ]
      }

      userGrowthChart.setOption(userGrowthOption)
    }

    // 用户地域分布图表
    if (userRegionChartRef.value) {
      if (!userRegionChart) {
        userRegionChart = echarts.init(userRegionChartRef.value)
      }

      const userRegionOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: userAnalysisData.userRegionDistribution.map(item => item.region)
        },
        series: [
          {
            name: '用户分布',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: userAnalysisData.userRegionDistribution.map(item => ({
              value: item.count,
              name: item.region
            }))
          }
        ]
      }

      userRegionChart.setOption(userRegionOption)
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  // 模拟数据
  userAnalysisData.totalUserCount = 1256
  userAnalysisData.newUserCount = 128
  userAnalysisData.activeUserCount = 856
  userAnalysisData.averageOrderAmount = 108.50
  userAnalysisData.totalUserGrowth = 5.2
  userAnalysisData.newUserGrowth = 12.3
  userAnalysisData.activeUserGrowth = 3.7
  userAnalysisData.averageOrderGrowth = -1.2

  userAnalysisData.userGrowthTrend = [
    { date: '2023-01', totalUserCount: 1000, newUserCount: 100, activeUserCount: 700 },
    { date: '2023-02', totalUserCount: 1080, newUserCount: 80, activeUserCount: 720 },
    { date: '2023-03', totalUserCount: 1150, newUserCount: 70, activeUserCount: 750 },
    { date: '2023-04', totalUserCount: 1200, newUserCount: 50, activeUserCount: 800 },
    { date: '2023-05', totalUserCount: 1256, newUserCount: 56, activeUserCount: 856 }
  ]

  userAnalysisData.userRegionDistribution = [
    { region: '华东', count: 450 },
    { region: '华南', count: 320 },
    { region: '华北', count: 280 },
    { region: '西南', count: 120 },
    { region: '西北', count: 86 }
  ]

  userAnalysisData.userList = [
    {
      id: 1,
      username: 'user001',
      registerTime: '2023-01-15 10:25:36',
      lastLoginTime: '2023-05-20 15:30:42',
      orderCount: 12,
      totalSpent: 1256.50
    },
    {
      id: 2,
      username: 'user002',
      registerTime: '2023-02-05 14:12:18',
      lastLoginTime: '2023-05-19 09:45:23',
      orderCount: 8,
      totalSpent: 876.20
    },
    {
      id: 3,
      username: 'user003',
      registerTime: '2023-02-18 16:35:47',
      lastLoginTime: '2023-05-21 11:20:15',
      orderCount: 15,
      totalSpent: 1520.75
    },
    {
      id: 4,
      username: 'user004',
      registerTime: '2023-03-10 08:55:32',
      lastLoginTime: '2023-05-18 18:10:05',
      orderCount: 5,
      totalSpent: 520.30
    },
    {
      id: 5,
      username: 'user005',
      registerTime: '2023-03-25 11:40:19',
      lastLoginTime: '2023-05-20 20:25:38',
      orderCount: 10,
      totalSpent: 1050.80
    }
  ]

  total.value = 100

  // 渲染图表
  renderCharts()

  // 监听窗口大小变化，重新渲染图表
  window.addEventListener('resize', () => {
    userGrowthChart?.resize()
    userRegionChart?.resize()
  })

  // 实际项目中应该调用API获取数据
  // fetchUserAnalysisData()
})
</script>

<style scoped>
.users-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-content {
  text-align: center;
}

h2 {
  margin: 10px 0;
  font-size: 24px;
  color: #409EFF;
}

.up {
  color: #67C23A;
}

.down {
  color: #F56C6C;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

.search-box {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
